package com.artqiyi.dollmachine.common.Base;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.artqiyi.dollmachine.R;
import com.artqiyi.dollmachine.presenter.base.BasePresenter;
import com.artqiyi.dollmachine.presenter.base.BasePresenterCallback;
import com.artqiyi.dollmachine.views.widget.MultipleStatusView;
import com.artqiyi.dollmachine.views.widget.ToolBarView;

import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import timber.log.Timber;


/**
 * Fragment基类，默认实现懒加载，带Toolbar和MultipleStatusView
 */
public abstract class BaseFragment<P extends BasePresenter> extends Fragment implements IBaseView, BasePresenterCallback {
    private View mRootView;
    protected ToolBarView mToolBar;
    protected MultipleStatusView mMultipleStatusView;

    private boolean useLazyLoad = true;
    private boolean hadLoad = false;
    private boolean hadInit = false;
    protected boolean isVisibleToUser = false;
    private boolean isInViewPager = false;

    private long lastReloadTime = 0;

    //定义Presenter
    protected P mPresenter;
//    private CompositeSubscription mCompositeSubscription;


    @Override
    public boolean setUseLayoutIdCustom() {
        return false;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Timber.v("onCreateView");
        if (Build.VERSION.SDK_INT >= 21) {
            getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getActivity(), R.color.c7373ff));
        }
        if (setEventBusEnable()) {
            EventBus.getDefault().register(this);
        }
        if (mRootView != null) {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (parent != null) {
                parent.removeView(mRootView);
            }
        }

        if (setUseLayoutIdCustom()) {
            mRootView = inflater.inflate(getLayoutId(), container, false);
        } else {
            mRootView = inflater.inflate(R.layout.layout_base_view, container, false);
            mToolBar = (ToolBarView) mRootView.findViewById(R.id.toolBar);
            mMultipleStatusView = (MultipleStatusView) mRootView.findViewById(R.id.multipleStatusView);
            mToolBar.setFocusableInTouchMode(true);
            handleToolBar(mToolBar);
            mMultipleStatusView.setContentView(getLayoutId());
            mMultipleStatusView.setOnRetryClickListener(this);
        }

        mPresenter = getPresenter();
        if (mPresenter != null) {
            mPresenter.setView(this);
            mPresenter.setCallback(this);
            //用于RxBaseCallback显示load等对话框
            mPresenter.setContext(this.getActivity());
        }
//        mCompositeSubscription = new CompositeSubscription();
        ButterKnife.bind(this, mRootView);
        return mRootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Timber.v("onActivityCreated");
        hadInit = true;
        initView(savedInstanceState);
        useLazyLoad = setLazyLoadEnable();
        if (isInViewPager) {
            if (useLazyLoad) {
                setUserVisibleHint(isVisibleToUser);//初始化完成之后显示,解决第一个fragment不加载
            } else {
                loadData();
            }
        } else {
            loadData();
        }
    }


    protected abstract P getPresenter();


    public boolean setEventBusEnable() {
        return false;
    }

    @Override
    public MultipleStatusView getMultipleView() {
        return mMultipleStatusView;
    }

    /**
     * 在ViewPager中切换时，是否使用懒加载<br/>
     * 如果使用懒加载 ，在setUserVisibleHint中  -->初始化完成，没有加载过，可见，loadData
     * 如果不使用懒加载，在onActivityCreated中loadData
     */
    protected boolean setLazyLoadEnable() {
        return true;
    }


    /**
     * 只加载一次数据<br/>
     * 1.普通Fragment中onActivityCreated加载<br/>
     * 2.在ViewPager中切换时，如果使用懒加载 ，在setUserVisibleHint中  -->初始化完成，没有加载过，可见，loadData
     * 如果不使用懒加载，在onActivityCreated中loadData
     */
    @Override
    public void loadData() {
        Timber.v("loadData isInViewPager = %s", isInViewPager);
    }

    /**
     * 可见即加载数据，防抖使用{@link #reLoadDataDebounce()}<BR/>
     * 1.在TabHost中切换时，已创建的Fragment会隐藏，而再次显示时，不会调用onResume,
     * 在onResume中第一次loadData,在onHiddenChanged中再次loadData<BR/>
     * 2.配合使用ViewPager时，可见创建时会调用onResume,在切换可见时不会调用onResume只会调用setUserVisibleHint，
     * 并且setUserVisibleHint先于onAttach执行，<BR/>
     * 在onResume中第一次loadData，在ViewPager中切换可见时，如果初始化完成，在setUserVisibleHint中再次loadData.
     */
    @Override
    public void reLoadData() {
        Timber.v("reLoadData isInViewPager = %s", isInViewPager);
        if (System.currentTimeMillis() - lastReloadTime > setReloadDebounceTime()) {
            lastReloadTime = System.currentTimeMillis();
            reLoadDataDebounce();
        }
    }

    /**
     * 设置防抖时间，默认500ms，结合{@link #reLoadDataDebounce()}使用
     */
    public long setReloadDebounceTime() {
        return 500;
    }

    /**
     * 可见即加载 {@link #setReloadDebounceTime()}ms(默认500)内不会重复加载
     */
    public void reLoadDataDebounce() {
    }


    @Override
    public void onRetryClick(MultipleStatusView.ViewStatus viewStatus, View view) {
        loadData();
        reLoadData();
    }


    //------------------------------------Fragment的一些生命周期------------------------------------


    @Override
    public void onResume() {
        super.onResume();
        Timber.v("onResume");

        if (!isInViewPager || isVisibleToUser) {
            reLoadData();
        }

    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getArguments() != null) {
            handleArguments(getArguments());

        }
        isInViewPager = true;
        this.isVisibleToUser = isVisibleToUser;
        Timber.v("setUserVisibleHint Visible = %s", isVisibleToUser);
        if (hadInit && isVisibleToUser) {
            if (useLazyLoad && !hadLoad) {
                hadLoad = true;
                loadData();
            }
            reLoadData();
        }
    }

    protected void handleArguments(Bundle bundle) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Timber.v("onHiddenChanged hidden = %s", hidden);
        super.onHiddenChanged(hidden);
        if (!hidden) {
            reLoadData();
        }
    }

    @Override
    public void onDestroyView() {
        if (setEventBusEnable()) {
            EventBus.getDefault().unregister(this);
        }
        Timber.v("onDestroyView");
        hadLoad = false;
        hadInit = false;
        ButterKnife.unbind(this);
//        unSubscribe();
        super.onDestroyView();
    }

//    public void addSubscription(Subscription s) {
//        getCompositeSubscription().add(s);
//    }
//
//    public void unSubscribe() {
//        getCompositeSubscription().unsubscribe();
//    }
//
//    @Override
//    public CompositeSubscription getCompositeSubscription() {
//        return mCompositeSubscription;
//    }

    protected void handleToolBar(ToolBarView toolBar) {
//        toolBar.setVisibility(View.GONE);
    }


}
